package com.visualexpress.dao;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.hibernate.shards.strategy.ShardStrategyFactory;

import com.visualexpress.domain.Location;
import com.visualexpress.domain.Shipment;
import com.visualexpress.domain.TimeLocation;
import com.visualexpress.shards.HibernateSessionFactory;
import com.visualexpress.shards.TimeLocationShardStrategyFactory;
import com.visualexpress.shards.VEShardStrategyFactory;

/**
 * A data access object (DAO) providing persistence and search support for
 * TimeLocation entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see com.visualexpress.domain.TimeLocation
 * @author MyEclipse Persistence Tools
 */

public class TimeLocationDAO implements IBaseHibernateDAO {
	private static final Log log = LogFactory.getLog(TimeLocationDAO.class);
	private static ShardStrategyFactory ssf;
	// property constants
	private String id;
	private Shipment shipment;
	private Location location;
	private Date arrivalTime;
	private Date leaveTime;

	public static final String SHIPMENT = "shipment";
	public static final String LOCATION = "location";
	public static final String ARRIVAL_TIME = "arrivalTime";
	public static final String LEAVE_TIME = "leaveTime";

	public void save(TimeLocation transientInstance) {
		log.debug("saving TimeLocation instance");
		try {
			Session s = this.getSession();
			Transaction t = s.beginTransaction();
			s.save(transientInstance);
//			s.flush();
			t.commit();
//			s.close();
			System.out.println(transientInstance.getId());
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(TimeLocation persistentInstance) {
		log.debug("deleting TimeLocation instance");
		try {
			Session s = this.getSession();
			Transaction t = s.beginTransaction();
			s.delete(persistentInstance);
			t.commit();
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public TimeLocation findById(java.lang.Integer id) {
		log.debug("getting TimeLocation instance with id: " + id);
		try {
			TimeLocation instance = (TimeLocation) getSession().get(
					"com.visualexpress.domain.TimeLocation", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(TimeLocation instance) {
		log.debug("finding TimeLocation instance by example");
		try {
			List results = getSession().createCriteria(
					"com.visualexpress.domain.TimeLocation").add(
					Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}
	
	public List findByProperty(String propertyName, Object value) {
		log.debug("finding TimeLocation instance with property: "
				+ propertyName + ", value: " + value);
		try {
			getSession().flush();
			String queryString = "from TimeLocation as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByShipment(Shipment shipment) {
		shipment.getId();
		
		List<TimeLocation> tlList;
		
		try {
//			getSession().flush();
			String queryString = "from TimeLocation tl where tl.shipment='"+
					 shipment.getId() + "'";
			Query queryObject = getSession().createQuery(queryString);
			tlList=  queryObject.list();
			
			if(tlList!=null)
			{
				Collections.sort(tlList,
						new Comparator<TimeLocation>() {
							public int compare(TimeLocation o1, TimeLocation o2) {
								return o1.getLocationNumber() - o2.getLocationNumber(); 
							}
						});
			}
			return tlList;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
		
		
	}

	public List findByLocation(Object location) {
		return findByProperty(LOCATION, location);
	}
	
	public List findByArrivalTime(Object arrivalTime) {
		return findByProperty(ARRIVAL_TIME, arrivalTime);
	}
	
	public List findByLeaveTime(Object leaveTime) {
		return findByProperty(LEAVE_TIME, leaveTime);
	}

	public List findAll() {
		log.debug("finding all TimeLocation instances");
		try {
			String queryString = "from TimeLocation";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public TimeLocation merge(TimeLocation detachedInstance) {
		log.debug("merging TimeLocation instance");
		try {
			TimeLocation result = (TimeLocation) getSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(TimeLocation instance) {
		log.debug("attaching dirty TimeLocation instance");
		try {
			Session s = this.getSession();
			Transaction t = s.beginTransaction();
			s.saveOrUpdate(instance);
			t.commit();
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(TimeLocation instance) {
		log.debug("attaching clean TimeLocation instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	@Override
	public Session getSession() {
		if(ssf==null)
			ssf = new TimeLocationShardStrategyFactory();
		return HibernateSessionFactory.getSession(ssf);
	}
}